package com.cn.lcc.base.Interceptor;

import java.lang.reflect.Method;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.cn.lcc.base.annotation.FieldCheck;
import com.cn.lcc.base.annotation.ParametersCheck;
import com.cn.lcc.base.exception.InvalidSignException;
import com.cn.lcc.base.exception.ParameterException;
import com.cn.lcc.util.config.Config;
import com.cn.lcc.util.request.RequestContextUtil;
import com.cn.lcc.util.sign.SignUtil;


/**
 * @author lcc  
 * @date 2017年6月13日
 * @备注   参数校验
 */
public class ParameterCheckInterceptor extends HandlerInterceptorAdapter {

    private static final Logger logger = LoggerFactory
            .getLogger(ParameterCheckInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request,
            HttpServletResponse response, Object handler) throws Exception {
    	String sign = request.getParameter("sign");
        if (StringUtils.isEmpty(sign)) {
            throw new ParameterException(request, "签名不能为空");
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        ParametersCheck interceptor = method
                .getAnnotation(ParametersCheck.class);
        Map<String, String> signMap = RequestContextUtil.getContext();
        if (interceptor != null) {
            FieldCheck[] checks = interceptor.checks();
            for (FieldCheck check : checks) {
                if (!signMap.containsKey(check.name())) {
                    continue;
                }
                System.out.println("check.name="+check.name());
                System.out.println("signMap.get(check.name())="+signMap.get(check.name()));
                if (!check.allowNull()
                        && StringUtils.isEmpty(signMap.get(check.name()))) {
                    throw new ParameterException(request, check.desc() + "不能为空");
                }
                if (StringUtils.isNotEmpty(signMap.get(check.name()))
                        && signMap.get(check.name()).getBytes("GBK").length > check
                                .length()) {
                    throw new ParameterException(request, check.desc()
                            + "字节长度超出限制");
                }
            }
            if (!sign.equals(SignUtil.getSign(signMap,Config.getString("xxx.key")))) {
                logger.warn("签名错误,appkey={},key={}",signMap.get("appkey"),Config.getString("xxx.key"));
                throw new InvalidSignException();
            }
        }
        return true;
    }
}
